const app = getApp()
import axios from '../../utils/axios'


Page({

  data: {
    showCode: false,
    canvasWidth: "",
    canvasHeight: "",
    inviter: "",
    applyImg: ""
  },

  onLoad: function (options) {
    this.getShareCode()
  },

  onShow: function () {

  },

  // 海报生成
  shareCode: function () {
    wx.showLoading({
      title: '图片生成中...',
      mask: true
    })

    const self = this

    // const query = wx.createSelectorQuery().in(self)
    // query.select('.canvas-box').boundingClientRect(function (rect) {
    //   console.log("rect", rect)
    //   self.setData({
    //     canvasWidth: parseInt(rect.width),
    //     canvasHeight: parseInt(rect.height)
    //   })
    // }).exec();

    const ctx = wx.createCanvasContext('imgCanvas', self)
    let selfCodeImg = ""

    let codeImg = ""

    axios('/personal/unlimit', {
      scene: "?key=" + self.data.inviter,
      page: "pages/index/index"
    }).then(res => {
      if (res.data.resultcode == 1) {
        codeImg = res.data.result
      }
    }).then(() => {

      wx.downloadFile({
        url: codeImg,
        success(res) {
          selfCodeImg = res.tempFilePath

          ctx.drawImage("../../image/group/apply-qrcode.png", 0, 0, 280, 420)
          ctx.drawImage(selfCodeImg, 86, 240, 110, 110)

          ctx.draw(true, function () {
            wx.canvasToTempFilePath({
              x: 0,
              y: 0,
              destWidth: 280,
              destHeight: 420,
              canvasId: 'imgCanvas',
              success(res) {
                wx.hideLoading()
                self.setData({
                  applyImg: res.tempFilePath
                })
              }
            })
          })

        }
      })

    })

  },

  // 打开生成分享海报
  shareDetails: function () {
    this.setData({
      showCode: true
    })
    this.shareCode()
  },

  // 获取分享key
  getShareCode: function () {
    axios("/personal/shareCode").then(res => {

      if (res.data.resultcode == 1) {
        this.setData({
          inviter: res.data.result
        })
      }
    })
  },

  // 点击关闭分享海报
  closeModel: function () {
    this.setData({
      showCode: false
    })
  },

  saveImage: function () {
    let that = this
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum'] && res.authSetting['scope.writePhotosAlbum'] != undefined) {
          wx.openSetting({
            success(res) {
              if (!res.authSetting['scope.writePhotosAlbum']) {
                wx.showToast({
                  title: '请开启相册权限哦！',
                  icon: 'none',
                  duration: 1300
                })
              } else {
                that.saveCodeImg()
              }
            },
            fail(err) {
              console.log(err)
            }
          })
        } else {
          that.saveCodeImg()
        }
      }
    })

  },

  saveCodeImg() {
    let self = this
    wx.saveImageToPhotosAlbum({
      filePath: this.data.applyImg,
      success(res) {
        wx.showToast({
          title: '保存成功，可以去分享啦！',
          icon: 'none',
          duration: 1600
        })
        self.closeModel()
      },
      fail(err) {
        if (!err.errMsg.indexOf("fail cancel")) {
          wx.showToast({
            title: '请点击保存图片打开相册的权限哦！',
            icon: 'none',
            duration: 3000
          })
        }

      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    const self = this
    console.log("self.data.inviter==", self.data.inviter)
    return {
      title: "快来加入我的团队吧！全场宠物商品3折起，超多优惠等您来！",
      page: "/pages/index/index?key=" + self.data.inviter
    }
  }
})